<template>
  <el-dialog
    v-model="dialogVisible"
    v-if="load"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :title="title"
    width="936"
    @close="handleClose"
    draggable
    :z-index="2000"
  >
    <el-form
      ref="formRef"
      :model="form"
      label-align="right"
      label-width="0"
      size="default"
      label-position="top"
    >
      <el-card class="mb-4">
        <template #header>
          <div class="pictureTitle">人员信息</div>
        </template>
        <el-row class="person-info" :gutter="20" v-if="handleType === 'view'">
          <el-col :span="8">
            <div class="order-label">设计审核人：</div>
            <div class="order-value">{{ form.designer_reviewer_text || "--" }}</div>
          </el-col>
          <el-col :span="8">
            <div class="order-label">图片处理人员：</div>
            <div class="order-value">{{ form.designer_user_text || "--" }}</div>
          </el-col>
          <el-col :span="8">
            <div class="order-label">摄影人员：</div>
            <div class="order-value">{{ form.photography_user_text || "--" }}</div>
          </el-col>
          <el-col :span="8">
            <div class="order-label">编辑人员：</div>
            <div class="order-value">{{ form.edit_user_text || "--" }}</div>
          </el-col>
          <el-col :span="8">
            <div class="order-label">渲染人员：</div>
            <div class="order-value">{{ form.render_user_text || "--" }}</div>
          </el-col>
          <el-col :span="8">
            <div class="order-label">协助人员：</div>
            <div class="order-value">{{ form.assistance_user_text || "--" }}</div>
          </el-col>
          <el-col :span="24">
            <div class="order-label">任务备注：</div>
            <div class="order-value">{{ form.task_remark || "--" }}</div>
          </el-col>
        </el-row>
        <el-row :gutter="20" v-else>
          <el-col :span="6">
            <el-form-item label="设计审核人" required>
              <select-personnel
                v-model="form.designer_reviewer"
                placeholder="运营人员"
              ></select-personnel>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="图片处理人员">
              <select-personnel
                v-model="form.designer_user"
                placeholder="图片处理人员"
              ></select-personnel>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="摄影人员">
              <select-personnel
                v-model="form.photography_user"
                placeholder="摄影人员"
              ></select-personnel>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="编辑人员">
              <select-personnel
                v-model="form.edit_user"
                placeholder="编辑人员"
              ></select-personnel>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="渲染人员">
              <select-personnel
                v-model="form.render_user"
                placeholder="渲染人员"
              ></select-personnel>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="协助人员">
              <select-personnel
                v-model="form.assistance_user"
                placeholder="协助人员"
              ></select-personnel>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="任务备注">
              <el-input
                v-model="form.task_remark"
                :rows="2"
                type="textarea"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <el-card class="mb-4">
        <template #header>
          <div class="pictureTitle">任务标签</div>
        </template>
        <taskTag v-model="form.images_task_tag" @changeRole="changeRole"></taskTag>
      </el-card>
      <routineModule
        v-model="form.images_url_list"
        tips="注：此图片仅用于判断任务的完成情况，无法推送到产品资料，支持绑定图片绩效标签；"
      ></routineModule>
      <el-card class="mb-4">
        <template #header>
          <div class="pictureTitle">附件</div>
        </template>
        <FileUpload
          v-model="form.task_file"
          :isShowTip="false"
          :progress="true"
          v-if="handleType == 'edit' || handleType == 'add'"
        >
        </FileUpload>
        <el-row :gutter="20" v-else>
          <el-col :span="8" v-for="(item, index) in form.task_file" :key="index">
            <svg-icon icon-class="file" style="color: #ececec" />
            <el-tooltip :content="item.name" placement="top">
              <span class="file-name truncate">{{ item.name }}</span>
            </el-tooltip>
            <span class="a-down" @click="handleDown(item.url)">下载</span>
          </el-col>
        </el-row>
        <!-- <div class="text-[#999999]" v-else>暂无附件</div> -->
      </el-card>
    </el-form>
    <div class="text-[#999] mt-4">
      <p>注：</p>
      <p>1、非设计任务，用于处理无SKU的任务；例如：拍摄协助等。</p>
      <p>2、可绑定任务标签；用于核算绩效。</p>
      <p>3、任务创建后，设计审核通过后，自动完结。</p>
    </div>
    <template #footer>
      <el-button class="ml-auto" @click="handleClose">取消</el-button>
      <el-button
        v-if="handleType != 'view'"
        type="primary"
        :loading="loading"
        @click="addTaskFun"
      >
        保存
      </el-button>
    </template>
  </el-dialog>
  <dialogUpload ref="dialogUploadRef"></dialogUpload>
</template>

<script setup>
import { computed, onMounted, ref, toRefs, reactive } from "vue";
import { ElMessageBox, ElMessage } from "element-plus";
import dialogUpload from "./dialogUpload.vue";
import { createNotDesign, editNotDesign, getImagesAssignmentDetail } from "../api";
import { imageTypeText } from "../data.js";
import useCommonStore from "@/store/modules/common";
import routineModule from "../components/Picture/components/routineModule.vue";
import taskTag from "./taskTag.vue";
import FileUpload from "@/components/FileUpload";

const commonStore = useCommonStore();

const dialogVisible = ref(false);
const personnelOptions = computed(() => {
  if (!commonStore.personnelOptions) {
    commonStore.getOrganization();
  }
  return commonStore.personnelOptions;
});

onMounted(() => {
  if (!commonStore.personnelOptions) {
    commonStore.getOrganization();
  }
});

const data = reactive({
  form: {
    developer_user: "", //产品开发人员
    operators_user_ids: [], // 运营人员
    photo_processor: "", // 图片处理人员
    camera_processor: "", // 摄影人员
    edit_user: "", //编辑人员
    task_priority: "", // 任务等级/类型
    task_type: [], // 任务类型
    product_type: "", // 产品类型
    brand_id: "", // 涉及品牌
    expected_time: "", // 预期完成时间
    image_total: "", // 图片数量
    task_remark: "", // 任务备注
    task_file: [], // 任务文件
    text_file: [], // 文案文件
    spu: "",
    attr_type: "",
    images_url_list: [],
    images_task_tag: [],
  },
  handleType: null,
  PictureRef: null,
  title: null,
  activeName: null,
  goods_spu_gallery: [],
  checkedSPU: null,
  load: false,
  loading: false,
});

const {
  form,
  handleType,
  title,
  activeName,
  goods_spu_gallery,
  checkedSPU,
  load,
  loading,
} = toRefs(data);

provide("handleType", handleType);

// 保存图片任务
const addTaskFun = () => {
  const formData = Object.assign({}, form.value);
  formData.images_task_tag = formData.images_task_tag.filter((i) => {
    if (!i.type) {
      return i;
    }
  });
  loading.value = true;
  if (handleType.value == "edit") {
    editNotDesign({
      ...formData,
    })
      .then(() => {
        ElMessage({
          message: "修改成功",
          type: "success",
        });
        dialogVisible.value = false;
        emit("query");
      })
      .finally(() => {
        loading.value = false;
      });
  } else {
    createNotDesign(formData)
      .then(() => {
        ElMessage({
          message: "新增成功",
          type: "success",
        });
        dialogVisible.value = false;
        emit("query");
      })
      .finally(() => {
        loading.value = false;
      });
  }
};

const statusMap = new Map([
  ["add", "创建非设计任务"],
  ["edit", "编辑"],
  ["view", "查看"],
  ["copy", "新增"],
]);

const open = async (type, sample_spu) => {
  if (!load.value) {
    load.value = true;
    await 1;
  }
  title.value = statusMap.get(type);
  handleType.value = type;
  if (sample_spu) {
    getDetail(sample_spu);
  } else {
    form.value.images_task_tag.push({
      type: "add",
      images_tag: {},
    });
  }
  dialogVisible.value = true;
};

// 获取详情
const getDetail = (id) => {
  getImagesAssignmentDetail({ task_id: id }).then((res) => {
    const data = res.data;
    data.images_assignment_sku.forEach((item, index) => {
      item.images_assignment_list =
        item.images_assignment_list && item.images_assignment_list.length
          ? item.images_assignment_list.map((j) => {
              if (j.image_list.length == 0) {
                j.image_list = initGalleryContents();
              } else {
                j.image_list = matchAndAdd(
                  goods_spu_gallery.value[0].image_list,
                  j.image_list
                );
                j.image_list = j.image_list.sort(
                  (a, b) => gallerySort(a.type) - gallerySort(b.type)
                );
              }
              return j;
            })
          : initGallery(true);
    });
    if (handleType.value == "copy") {
      data.images_assignment_sku.forEach((item, index) => {
        item.spu = data.spu;
        item.images_assignment_list = initGallery(true);
      });
      delete data.status;
      delete data.status_text;
      delete data.create_time;
      delete data.expected_time;
      delete data.process_time;
      delete data.task_no;
      checkedSPU.value = [
        {
          spu: data.spu,
          category_id: data.category_id,
        },
      ];
    }

    form.value = data;
    form.value.images_task_tag.push({
      type: "add",
      images_tag: {},
    });
    // activeName.value = form.value.images_assignment_sku[0].sku
  });
};

const gallerySort = (type) => {
  if (type == 3) {
    return 0;
  } else {
    return type;
  }
};

const matchAndAdd = (array1, array2) => {
  for (var i = 0; i < array1.length; i++) {
    var isDuplicate = false;
    for (var j = 0; j < array2.length; j++) {
      if (array1[i].type === array2[j].type) {
        isDuplicate = true;
        break;
      }
    }
    if (!isDuplicate) {
      array2.push(array1[i]);
    }
  }
  return array2;
};

// 图片详情
const initGalleryContents = () => {
  let contents = [];
  imageTypeText.forEach((element, e) => {
    contents.push({
      label: element.label,
      image_type: element.value,
      showType: 0,
      values: [],
    });
  });
  return contents;
};

const handleClose = () => {
  initForm();
  emit("close");
  dialogVisible.value = false;
};

// 初始化form
const initForm = () => {
  form.value = {
    developer_user: "", //产品开发人员
    operators_user_ids: [], // 运营人员
    photo_processor: "", // 图片处理人员
    camera_processor: "", // 摄影人员
    edit_user: "", //编辑人员
    task_priority: "", // 任务等级/类型
    task_type: [], // 任务类型
    product_type: "", // 产品类型
    brand_id: "", // 涉及品牌
    expected_time: "", // 预期完成时间
    image_total: "", // 图片数量
    task_remark: "", // 任务备注
    task_file: [], // 任务文件
    text_file: [], // 文案文件
    spu: "",
    attr_type: "",
    images_url_list: [],
    images_task_tag: [],
  };
};

const emit = defineEmits(["close", "query"]);

defineExpose({ open });

const changeRole = (item) => {
  if (!form.value[item.ruleType]) {
    ElMessage.error("请维护对应角色的人员");
  }
  console.log(form.value[item.ruleType]);
  console.log(item.ruleType);

  form.value.images_task_tag[item.index].user_id = form.value[item.ruleType];
  form.value.images_task_tag[item.index].username = findUserNamesById(
    form.value[item.ruleType]
  );
};

const findUserNamesById = (userIds) => {
  if (!userIds) return "";

  const options = personnelOptions.value; // 从外部获取用户数据

  console.log(options);
  console.log(userIds);

  const selectedUserNames = new Set();

  const dfs = (node) => {
    if (!node) return;
    if (node.user_id === userIds) {
      selectedUserNames.add(node.name);
    }

    if (node.sub && node.sub.length > 0) {
      for (const subNode of node.sub) {
        dfs(subNode);
      }
    }
  };

  for (const option of options) {
    dfs(option);
  }

  return Array.from(selectedUserNames)[0]; // 返回找到的用户名数组
};
</script>
<style lang="scss" scoped>
:deep(.el-scrollbar__view) {
  overflow-y: hidden;
}

:deep(.el-tabs__header) {
  margin-bottom: 0;
}

.listMr {
  margin-right: 18px;

  &:nth-of-type(6n + 6) {
    margin-right: 0;
  }
}

.listMrVideo {
  margin-right: 19px;

  &:nth-of-type(4n + 4) {
    margin-right: 0;
  }
}

.pictureTitle {
  font-weight: bold;
  position: relative;
  padding-left: 6px;
  font-size: 16px;
  color: var(--base-sub-text-color);

  &::after {
    content: "";
    height: 14px;
    width: 2px;
    position: absolute;
    left: 0;
    top: 5px;
    align-items: center;
    background-color: #3366f1;
  }
}

.item_width {
  width: 566px;
}

// .order-info {
.pictureTitle {
  // padding: 16px 0 16px 4px;
  position: relative;
  font-size: 16px;
  color: var(--base-sub-text-color);
  font-weight: 500;
  display: inline-block;
}

// .pictureTitle::after {
//   content: "";
//   height: 14px;
//   width: 2px;
//   position: absolute;
//   left: 0;
//   top: 50%;
//   margin-top: -8px;
//   align-items: center;
//   background-color: #3366f1;
// }

.order-desc {
  padding-bottom: 8px;
  font-size: 14px;
  color: #3a4259;
}

.spu-txt {
  color: #3a4259;
  font-size: 14px;
}

.order-label,
.order-value {
  display: inline-block;
  line-height: 30px;
}

.order-label {
  color: #999;
  width: 100px;
  text-align: right;
}

.order-value {
  color: #333;
}

:deep(.upload-file-uploader) {
  .el-upload.el-upload--text {
    button.el-button {
      padding: 8px 0;
    }
  }
}
</style>
<style lang="scss">
.hidden-row {
  display: none;
}
</style>
